package me.firstapp.spi.system.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.system.JsonStatistics;
import me.firstapp.spi.base.impl.BaseServiceImpl;
import me.firstapp.spi.system.StatisticsService;

@Service
public class StatisticsServiceImpl extends BaseServiceImpl implements StatisticsService {

	@Override
	public SingleObject<JsonStatistics> findStatistics() {
		SingleObject<JsonStatistics> result = new SingleObject<>();
		try {
			Map<String, Object> parameters = new HashMap<>();
			JSONObject resultObject = api(parameters, "/statistics/findStatistics.do", HttpMethod.GET, "获取统计信息");

			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultObject.getString("code"))) {
				JsonStatistics statistics = JSONObject.toJavaObject(resultObject.getJSONObject("object"),
						JsonStatistics.class);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
				result.setObject(statistics);
			} else {
				throw new ServiceException(resultObject.getString("code"), resultObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

	@Override
	public SingleObject<JsonStatistics> executeStatistics(Long apiClientId) {
		SingleObject<JsonStatistics> result = new SingleObject<>();
		try {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("apiClientId", apiClientId);
			JSONObject resultObject = api(parameters, "/batch/executeStatistics.do", HttpMethod.POST, "统计信息");

			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultObject.getString("code"))) {
				JsonStatistics statistics = JSONObject.toJavaObject(resultObject.getJSONObject("object"),
						JsonStatistics.class);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
				result.setObject(statistics);
			} else {
				throw new ServiceException(resultObject.getString("code"), resultObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

}
